package cn.jussi.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.jussi.model.UploadFile;
import cn.jussi.service.ServiceFactory;
import cn.jussi.service.UploadFileService;

@WebServlet(urlPatterns= {"*.up"})
public class UploadFileController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	UploadFileService ufs = ServiceFactory.getUploadFileService();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		String mn = req.getServletPath();
		mn = mn.substring(1, mn.length()-3);
		try {
			Method method = this.getClass().getDeclaredMethod(mn, HttpServletRequest.class, HttpServletResponse.class);
			method.invoke(this, req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
	
	@SuppressWarnings("unused")
	private void upload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//保存接受到的文件， 转发到service实现具体的业务逻辑
		try {
			ufs.saveFile(req, resp);
			resp.sendRedirect(req.getContextPath()+"/index.up");
		} catch (Exception e) {
			//获得异常信息，注入jsp页面显示
			req.setAttribute("errorMsg", e.getMessage());
			req.getRequestDispatcher("/index.up").forward(req, resp);
		}
	}
	
	@SuppressWarnings("unused")
	private void index(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<UploadFile> list = ufs.getUploadFilesInfo();
		req.setAttribute("uploadFiles", list);
		req.getRequestDispatcher("/index.jsp").forward(req, resp);
	}
	
	@SuppressWarnings("unused")
	private void deleteFile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int id = Integer.parseInt(req.getParameter("id"));
		ufs.deleteUploadFileInfo(id);
		resp.sendRedirect(req.getContextPath()+"/index.up");
	}
	
	@SuppressWarnings("unused")
	private void downloadFile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1.获取下载文件的绝对路径
		int id = Integer.parseInt(req.getParameter("id"));
		UploadFile uf = ufs.getUploadFilesById(id);
		String filePath = uf.getSavePath()+"\\"+uf.getSaveName();
		//2.获取要下载的文件名
		String fileName = uf.getOldFileName();
		//解决下载时，中文名中文乱码
		String userAgent = req.getHeader("User-Agent");
		if(userAgent.contains("MSIE") || userAgent.contains("Trident")) {
			//针对IE或者以IE为内核的浏览器
			fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
		}else {
			//非IE浏览器的处理
			fileName = new String (fileName.getBytes("UTF-8"), "ISO-8859-1");
		}
		//3.设置context-disposition响应头控制浏览器以下载的方式打开文件
		resp.setHeader("content-disposition", "attachment;filename="+fileName);	
		//4.获取要下载的文件输入流
		InputStream in = new FileInputStream(filePath);
		//5.创建缓冲区
		int len = 0;
		byte[] buffer = new byte[1024];
		//6.通过response对象获取OutputSteam输出流对象
		OutputStream os = resp.getOutputStream();
		//7.将FileInputStream流对象写入到buffer缓冲区
		while((len=in.read(buffer))>0) {
			os.write(buffer, 0, len);
		}
		//8.关闭流
		in.close();
		os.close();
	}	
}
